package com.zz.concurrent.thread;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Scanner;

/**
 * Author: zhangzhen
 * DATE: Created in 2018/8/15 14:13
 * Description:
 */
class DaemondThreadDemo implements Runnable {

    @Override
    public void run() {
        System.out.println("进入守护线程" + Thread.currentThread().getName());
        try {
            writeToFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("退出守护线程" + Thread.currentThread().getName());
    }
    private void writeToFile() throws Exception{
        File fileName = new File("d:" + File.separator + "daemon.txt");
        OutputStream os = new FileOutputStream(fileName, true);
        int count = 0;
        while(count < 99) {
            os.write(("\r\nword" + count).getBytes());
            System.out.println("守护线程" + Thread.currentThread().getName() + "向文件中写入了word" + count++);
            Thread.sleep(1000);
        }
    }
}
public class DaemondThread {

    public static void main(String[] args) {
        System.out.println("程序进入了主线程" + Thread.currentThread().getName());
        DaemondThreadDemo daemondThreadDemo = new DaemondThreadDemo();
        Thread thread = new Thread(daemondThreadDemo);
        thread.setDaemon(true);
        thread.start();

        Scanner sc = new Scanner(System.in);
        sc.next();

        System.out.println("程序退出了主线程" + Thread.currentThread().getName());
    }

}
